package jmine.tec.utils.spring.http;

import java.io.Serializable;

import jmine.tec.utils.spring.InstanceResolver;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

/**
 * Delegates instance resolving to a {@link BeanFactory}.
 * 
 * @author takeshi
 * @param <E> the type
 */
public final class BeanFactoryInstanceResolver<E> implements InstanceResolver<E>, BeanFactoryAware, Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -1859589782569274349L;

    private final String beanName;

    private BeanFactory beanFactory;

    /**
     * @param beanName the bean name
     */
    public BeanFactoryInstanceResolver(final String beanName) {
        super();
        this.beanName = beanName;
    }

    /**
     * Does nothing - wont affect the underlying {@link BeanFactory}
     */
    public void clear() {
    }

    /**
     * Does nothing - wont affect the underlying {@link BeanFactory}
     */
    public void clearCurrentInstance() {
    }

    /**
     * @return E
     */
    @SuppressWarnings("unchecked")
    public E getInstance() {
        if (this.beanFactory == null) {
            throw new NullPointerException("BeanFactory cannot be null!");
        }
        if (this.beanFactory != null && this.beanFactory.containsBean(this.beanName)) {
            return (E) this.beanFactory.getBean(this.beanName);
        }
        return null;
    }

    /**
     * Does nothing - wont affect the underlying {@link BeanFactory}
     * 
     * @param object E
     */
    public void setInstance(final E object) {
    }

    /**
     * @param beanFactory the {@link BeanFactory}
     */
    public void setBeanFactory(final BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

}
